package application.messager;

import java.util.ArrayList;
import java.util.List;

/**
 * 消息分发平台
 */
public class MessageCenter {

    /**
     * 消息接收者的注册中心
     */
    private List<MessageReceiver> messageReceivers;

    /**
     * 消息中心唯一对象存放属性
     */
    private static MessageCenter messageCenter = new MessageCenter();

    /**
     * 消息中心无参构造方法
     */
    private MessageCenter() {
        messageReceivers = new ArrayList<>();
    }

    /**
     * 通过此方法，获取消息中心的唯一对象
     * @return
     */
    public static MessageCenter getInstance() {
        if (messageCenter == null) {
            messageCenter = new MessageCenter();
        }
        return messageCenter;
    }

    /**
     * 通过此方法，注册消息接收者
     * @param messageReceiver
     */
    public void register(MessageReceiver messageReceiver) {
        if (this.messageReceivers.contains(messageReceiver)) {
            return;
        }
        this.messageReceivers.listIterator().add(messageReceiver);
    }

    /**
     * 调用此方法注销消息接收者。
     * @param messageReceiver
     */
    public void unregister(MessageReceiver messageReceiver) {
        if (this.messageReceivers.contains(messageReceiver)) {
            this.messageReceivers.remove(messageReceiver);
        }
    }

    /**
     * 当Messager对象调用sendMessage方法时会调用到此方法，通知等待消息的MessageReceiver
     * @param messager 消息携带者，它携带者要传递的消息。
     */
    void notifyMessageReceiver(Messager messager) {
        for (MessageReceiver messageReceiver : this.messageReceivers) {
            if (!messageReceiver.hasAction()) {
                continue;
            }
            if (messageReceiver.isExist(messager.getAction())) {
                boolean result = messageReceiver.receive(messager);
                if (result) {
                    return;
                }
            }
        }
    }
}
